﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Diagnostics;
using BReusable;

namespace BReusable.PivotalTracker
{
	public class PivotalTrackerToken
	{
		public const string StrPivotalTrackerTokens = "https://www.pivotaltracker.com/services/tokens/active";
		public string Token { get; set; }

		private readonly WebProxy _proxy; 

		public PivotalTrackerToken( string proxyLocation,int proxyPort)
		{
			_proxy = new WebProxy(proxyLocation, proxyPort);
		}
		public PivotalTrackerToken( string proxyLocation,int proxyPort,string uid,String pwd):this(proxyLocation,proxyPort)
		{
			Token = GetToken(uid, pwd);
			Debug.Assert(Token.IsNullOrEmpty() == false);
		}
		public PivotalTrackerToken(string proxyLocation, int proxyPort, string token)
			: this(proxyLocation, proxyPort)
		{
			Token = token;
		}
			public string GetToken(string uid, string pwd)
		{
			var results = GetTokenXML(uid, pwd);
			var regex=new System.Text.RegularExpressions.Regex("<guid>([0-9a-z]+)</guid>", 
				System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			if (regex.IsMatch(results))
			{
				var match = regex.Match(results);
			return	match.Groups[1].Captures[0].Value;
			}
				return null;
		}
			public string GetTokenXML(string uid, string pwd)
			{
				var request = BHttpLib. GetRequestWithProxyBasicAuthentication(new Uri(StrPivotalTrackerTokens), _proxy, uid /*.Replace("'", "%27")*/
			, pwd);
				return BHttpLib.FromRequestGetResponseString(request);
			}

			public HttpWebRequest GetRequest(Uri location)
			{
                var request = BHttpLib.ConstructHttpRequest(location, _proxy);
				AddTokenHeader(request);
				return request;
			}
			public HttpWebRequest GetPagePost(Uri location, IDictionary<string, string> postData)
			{
                var request = BHttpLib.ConstructHttpRequest(location, postData, _proxy);
				AddTokenHeader(request);
				return request;
			}
			public HttpWebRequest GetPagePostXML(Uri location, string xmlData)
			{
                var request = BHttpLib.ConstructHttpRequestXml(location, xmlData, _proxy);
				AddTokenHeader(request);
				return request;
			}

/*
			private string getPagePostXml(string location, string xmlData)
			{
				var request = HttpLib.GetRequestWithProxyXml(new Uri(location), _proxy, xmlData);

				return HttpLib.FromRequestGetResponseString(request);
			}
*/

		private void AddTokenHeader(WebRequest request)
		{
			request.Headers.Add("token", Token);
		}
		
	}
}
